<html>
<body onload="startTest()">

<script src="../../resources/js-test.js"></script>

<script>

description("This test checks that the page visibility event propagation does not crash the browser when frames are added / deleted.");

var jsTestIsAsync = true;

var frame1, frame2, frame3, frame4, frame5, subframe1, subFrame2, subFrame3;

var docsLoaded = 0;

function startTest() {
    ++docsLoaded;
    if (docsLoaded < 8) {
      return;
   }

    debug("Loaded all frames.");

    frame1 = document.getElementById("topFrame1");
    frame2 = document.getElementById("topFrame2");
    frame3 = document.getElementById("topFrame3");
    frame4 = document.getElementById("topFrame4");
    subFrame1 = frame3.contentDocument.getElementById("subIframe1");
    subFrame2 = frame3.contentDocument.getElementById("subIframe2");

    document.addEventListener(
        "visibilitychange", onMainPageVisibilityChange, false);
    frame2.contentDocument.addEventListener(
        "visibilitychange", onFrame2VisibilityChange, false);
    // Change the visibility of the current page to invisible.
    if (window.testRunner)
        testRunner.setMainWindowHidden(true);
}

function onMainPageVisibilityChange() {
    debug("Visibility of main document changed.");
    // Delete frame 4.
    document.body.removeChild(frame4);

    // Delete subframe 2.
    frame3.contentDocument.body.removeChild(subFrame2);

    // Add a new frame to top level.
    frame5 = document.createElement("iframe");
    frame5.src = '';
    document.body.appendChild(frame5);

    // Add a new frame to frame2.
    subFrame3 = frame2.contentDocument.createElement("iframe");
    subFrame3.src = '';
    frame2.contentDocument.body.appendChild(subFrame3);
}

function onFrame2VisibilityChange() {
    debug("Visibility of sub frame 2 changed.");
    // Delete frame 1.
    document.body.removeChild(frame1);
    finishJSTest();
}

</script>


<iframe id="topFrame1" onload="startTest()" ></iframe>
<iframe id="topFrame2" onload="startTest()" ></iframe>
<iframe id="topFrame3" onload="startTest()" src="resources/page-visibility-iframe-with-subframes.html"></iframe>
<iframe id="topFrame4" onload="startTest()" ></iframe>
</body>
</html>
